package com.qdxht.dispenser.view.loading;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import com.facebook.drawee.view.SimpleDraweeView;
import com.qdxht.dispenser.R;
import com.qdxht.dispenser.utils.MLog;
import com.qdxht.dispenser.utils.image.FrescoImageLoader;


public class LoadingBar {
    private final String TAG = "LoadingBar";

    private Dialog loadingDialog;

    private static LoadingBar instance;

    private LoadingBar() {
    }

    public static LoadingBar getInstance() {
        if (instance == null) {
            instance = new LoadingBar();
        }
        return instance;
    }

    /**
     * 显示Loading
     * @param context
     */
    public void show(Context context, boolean cancelable) {
        cancel();

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.view_loading_dialog, null);// 得到加载view

        SimpleDraweeView simpleDraweeView = (SimpleDraweeView) v.findViewById(R.id.sdv_loading);
        FrescoImageLoader.dispalyFromAssets("loading.gif", simpleDraweeView);

        loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog

        loadingDialog.setCancelable(cancelable);// 不可以用“返回键”取消
        loadingDialog.setCanceledOnTouchOutside(cancelable);
        loadingDialog.setContentView(v, new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));// 设置布局
        try {
            MLog.d(TAG, "show dialog!");
            loadingDialog.show();
        } catch (Exception e) {
        }

    }

    public void show(Context context) {
        show(context, false);
    }


    public boolean isShow() {
        if (loadingDialog != null) {
            return loadingDialog.isShowing();
        }
        return false;
    }

    /**
     * 关闭Loading
     */
    public void cancel() {
        try {
            if (loadingDialog != null) {
                MLog.d(TAG, "cancel dialog!");
                loadingDialog.cancel();
                loadingDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
